<?php
/**
 * Generator used to create domain objects base classes
 * @author Artur Kmera <artur.kmera@3code.pl>
 * @version 0.9
 * @package ORM
 * @subpackage Schema
 * @link http://arrowplatform.org/orm
 * @copyright 2011 Arrowplatform 
 * @license GNU LGPL
*/
class BaseDomainClassGenerator {
	/**
	 * Line separator (ending) constant
	 * @var string
	 */
	const ls = "\n";
	/**
	 * Dir whitch will be used to place generated classes
	 * @var string
	 */
	public $targetDir = "../cache/";
	
	
	/**
	 * Generate all schema classes ( from tables )
	 * @param Schema $schema
	 */
	public function generate( Schema $schema ){
		foreach($schema->getTables() as $table){
			file_put_contents($this->targetDir."ORM_".$table->getClass().".php", $this->generateClass($table));
		}
	}
	
	/**
	 * Generate class code
	 * @param Table $table
	 * @return string
	 */
	private function generateClass(Table $table){
		$str = "";
		$this->pl( "<?php", $str);
		$this->pl( "class ORM_{$table->getClass()} extends {$table->getBaseClass()}{", $str);
		$tmpFields = array();
		foreach($table->getFields() as $field){
			$tmpFields[] = $field->getName();
		}
		$this->pl( "protected static \$fields = array( '".implode("', '", $tmpFields) ."' );", $str, 1);
		$this->pl( "protected static \$table = \"{$table->getTableName()}\";", $str, 1);
		$this->pl( "protected static \$class = \"{$table->getClass()}\";", $str, 1);
		$this->pl( "protected static \$classPath = \"{$table->getClasspath()}\";", $str, 1);
		$this->pl( "}", $str);
		$this->pl( "?>", $str);
		return $str;
	}

	/**
	 * Helper to generate line of code with ident
	 * @param string $line
	 * @param string $string reference to string to place new line
	 * @param int $ident number of tabulators before line
	 */
	private function pl( $line, &$string, $ident = 0 ){
		$string.= str_repeat("\t", $ident).$line.self::ls;
	}
	
	
}
?>